#include "writeColors.hpp"
#include "Log.hpp"
#include <algorithm>
using namespace std;
using namespace m3g;

/**
 *
 */
unsigned int writeColors (M3GWriter* writer, MQDocument mq_doc, MQObject mq_obj, float* scale_, float* bias_)
{
    int material_count = mq_doc->GetMaterialCount ();
	int vertex_count   = mq_obj->GetVertexCount ();
	int face_count     = mq_obj->GetFaceCount ();

    bool vertex_color_enabled = false;
    for (int m = 0; m < material_count; m++) {
        if (mq_doc->GetMaterial(m)->GetVertexColor() == MQMATERIAL_VERTEXCOLOR_DIFFUSE) {
            vertex_color_enabled = true;
        }
    }
    if (!vertex_color_enabled) {
        return 0;
    }

	int* vertex_colors = new int[vertex_count];

	for (int f = 0; f < face_count; f++) {
		int face_vertex_count = mq_obj->GetFacePointCount(f);
		int face_vertex_indices[4];
		mq_obj->GetFacePointArray (f, face_vertex_indices);
		for (int v = 0; v < face_vertex_count; v++) {
			vertex_colors[face_vertex_indices[v]] = mq_obj->GetFaceVertexColor (f, v);
		}
	}

    int component_size  = 1;
    int component_count = 4;

	M3GObject3DStruct    obj;
	M3GVertexArrayStruct varry;
	varry.component_size  = component_size;
	varry.component_count = component_count;
	varry.encoding        = M3GVertexArrayStruct::ENCODING_0;
	varry.vertex_count    = vertex_count;
	varry.char_components = new char*[vertex_count];
	for (int v = 0; v < vertex_count; v++) {
		int abgr =  vertex_colors[v];
		varry.char_components[v]    = new char[4];
		varry.char_components[v][0] = (abgr & 0x000000ff) >> 0;  // r
		varry.char_components[v][1] = (abgr & 0x0000ff00) >> 8;  // g
		varry.char_components[v][2] = (abgr & 0x00ff0000) >> 16; // b
		varry.char_components[v][3] = (abgr & 0xff000000) >> 24; // a
	}

	unsigned int object_index;

	writer->startObject       (M3G_TYPE_VERTEX_ARRAY, &object_index);
	writer->writeObject3D     (obj);
	writer->writeVertexArray  (varry);
	writer->endObject         ();

  	delete[] vertex_colors;

    *scale_  = 1/255.f;
	bias_[0] = 0;
	bias_[1] = 0;
	bias_[2] = 0;

    Log:: print (" [%d] Write VertexArray(colors) : ", object_index);
    Log:: print (" vertex_count=%d"      , vertex_count   );
    Log:: print (", component_count=%d"  , component_count);
    Log:: print (", component_size=%d.\n", component_size );

    return object_index;
}